"""identity properties jsonb to json

Revision ID: fdcdafdb11cf
Revises: 549eff097c71
Create Date: 2025-02-21 10:30:49.937854

"""

from typing import Sequence, Union

import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

from alembic import op

# revision identifiers, used by Alembic.
revision: str = "fdcdafdb11cf"
down_revision: Union[str, None] = "549eff097c71"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.execute("ALTER TABLE identities ALTER COLUMN properties DROP DEFAULT")
    op.alter_column(
        "identities",
        "properties",
        existing_type=postgresql.JSONB(astext_type=sa.Text()),
        type_=postgresql.JSON(astext_type=sa.Text()),
        existing_nullable=False,
        postgresql_using="properties::text::json",
    )
    op.execute("ALTER TABLE identities ALTER COLUMN properties SET DEFAULT '[]'::json")
    op.execute("ALTER TABLE identities DROP CONSTRAINT IF EXISTS unique_identifier_key_project_id")
    op.create_unique_constraint(
        "unique_identifier_key_project_id_organization_id",
        "identities",
        ["identifier_key", "project_id", "organization_id"],
    )
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(
        "unique_identifier_key_project_id_organization_id", "identities", type_="unique"
    )
    op.create_unique_constraint(
        "unique_identifier_key_project_id", "identities", ["identifier_key", "project_id"]
    )
    op.execute("ALTER TABLE identities ALTER COLUMN properties DROP DEFAULT")
    op.alter_column(
        "identities",
        "properties",
        existing_type=postgresql.JSON(astext_type=sa.Text()),
        type_=postgresql.JSONB(astext_type=sa.Text()),
        existing_nullable=False,
        postgresql_using="properties::text::jsonb",
    )
    op.execute("ALTER TABLE identities ALTER COLUMN properties SET DEFAULT '{}'::jsonb")
    # ### end Alembic commands ###
